'''
Created on 28 mei 2009

@author: rlindeman
'''

import os
import sys, traceback

import rai.file
from rai.tagger.sentenceparser import *
from rai.sem.FOL import *


DEFAULT_SENTENCES_FILE = "solverfacts.txt"

class SentenceReader:
    """
        Reads sentences from a file and convert them to parsedSentences
    """

    def parseFile(self, filename = None, maxlines = 0, collapse_PP=True):
        """
            Reads sentences from a file and parses them
            @param filename: name of the file (absolutepath)
            @param maxlines: number of lines to read. Use value -1 to read the complete file
            @param collapse_PP: collapse a PP ("in") with the next NP ("the house") to a single PP-part ("in the house")
            @return: a list of parsed sentences  
        """
        if (filename is None):
            filename = DEFAULT_SENTENCES_FILE

        #__dir__ = rai.file.__path__
        #file_location = __dir__[0] + "\\" + filename
        f = open(filename, 'r')
        #org_grammar = "file:" +__dir__[0] + "\\org.world.test.fcfg"
        #print org_grammar

        parser = SentenceParser()
        parsedSentences = [] # list of sentences that were analyzed and added to the grammar rules

        exceptions = []
        i = 0
        lastLine = ""
        line = f.readline()
        while i < maxlines or (maxlines == -1 and line is not None and len(line)>0):
            if line is not None and len(line)>0:
                try:
                    parsed_sentence = parser.parseSentence(line, collapse_PP=collapse_PP)
                    parsedSentences.append(parsed_sentence)
                    #s [['VP', 'to'], ['VP', 'have', 'given']]
                    #s [['VP', ('to', 'TO', 'TO')], ['VP', ('have', 'HV', 'VBP'), ('given', 'VBN', 'VBN')]]
                except Exception, inst:
                    print inst
                    traceback.print_exc(file=sys.stdout)
                    exceptions.append(inst)
            
            lastLine = line   
            line = f.readline()
            i = i + 1
    
        for e in exceptions:
            print e
        return parsedSentences